package com.example.li893.drag;


import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.Spinner;


import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


public class MainActivity extends AppCompatActivity {
    private int i=0;
    private Spinner setColumn;
    private Button addItem;
    List<Item> itemList = new ArrayList<>();
    MyAdapter myAdapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        for (i = 0;i < 40; i ++){
            itemList.add(new Item(R.mipmap.ic_launcher, "组件" + i));
        }
        final DragView mDragView = (DragView) findViewById(R.id.dragview);
        //设置ListView的数据适配器
        myAdapter=new MyAdapter(this,itemList);
        mDragView.setAdapter(myAdapter);

        mDragView.setOnChangeListener(new DragView.OnChangeListener(){
            @Override
            public void onChange(int from, int to) {
                if(from < to){
                    for(int i=from; i<to; i++){
                        Collections.swap(itemList, i, i+1);
                    }
                }else if(from > to){
                    for(int i=from; i>to; i--){
                        Collections.swap(itemList, i, i-1);
                    }
                }

                myAdapter.notifyDataSetChanged();

            }
        });

        mDragView.setOnDeleteListener(new DragView.OnDeleteListener(){
            @Override
            public void onDelete(int from, int to) {
                    itemList.remove(to);
                myAdapter.notifyDataSetChanged();
            }
        });


        setColumn =findViewById(R.id.setColumn);
        setColumn.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String result=parent.getItemAtPosition(position).toString();
                int number=Integer.parseInt(result);
                DragView dragView  = (DragView) findViewById(R.id.dragview);
                dragView.setNumColumns(number);

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        addItem =findViewById(R.id.addItem);
        addItem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                itemList.add(new Item(R.mipmap.ic_launcher, "组件" + i));
                i++;
                myAdapter.notifyDataSetChanged();
            }
        });

    }

}
